<template>
  <van-button size="small" type="success" @click.prevent="sendSms" :disabled="isSendSms">{{
    btnText
  }}</van-button>
</template>


<script>
import { showNotify } from 'vant'
import { ajax } from '@/utils/ajax'
import { SystemApis } from '@/utils/apis'

export default {
  props: ['phone'],
  data() {
    return {
      // 判断发送按钮是否可点击
      isSendSms: false,
      btnText: '发送验证码',
      // 倒计时
      counter: 5,
      // 计时器
      timer: null
    }
  },
  methods: {
    reset() {
      clearInterval(this.timer)
      this.timer = null
      this.counter = 5
      this.btnText = '发送验证码'
      this.isSendSms = false
    },
    startCount() {
      this.timer = setInterval(() => {
        this.btnText = `${this.counter}秒后可重新发送`
        this.counter--

        if (this.counter < 0) {
          this.reset()
        }
      }, 1000)
    },
    sendSms() {
      // 检查手机号是否输入
      if (!this.phone) {
        // 3 秒后自动关闭
        showNotify({ type: 'danger', message: '请输入正确的手机号码' })
        return false
      }
      // 调用短信获取接口
      ajax
        .post(SystemApis.sendSmsCodeUrl, {
          phone: this.phone
        })
        .then(({ data }) => {
          console.log('smscode res:', data)
          showNotify({
            type: 'success',
            duration: 1000 * 8,
            message: `验证码是${data.sms_code}，有效期是${data.timeout / 60}分钟`
          })
        })
        .catch((err) => {
          showNotify('服务器正忙，请稍后重试')
          console.log(err)
        })
      // 按钮状态改变
      this.isSendSms = true
      // 开始倒计时
      this.startCount()
    }
  }
}
</script>